import Vue from 'vue'
import VueRouter from 'vue-router'

import MyLogin from '@/components/MyLogin.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/login', component: MyLogin },
  {
    path: '/home',
    component: () => import('@/components/MyHome.vue'),
    children: [
      { path: 'users', component: () => import('@/components/menus/MyUsers') },
      {
        path: 'orders',
        component: () => import('@/components/menus/MyOrders.vue')
      },
      {
        path: 'rights',
        component: () => import('@/components/menus/MyRights.vue')
      },
      {
        path: 'settings',
        component: () => import('@/components/menus/MySettings.vue')
      },
      {
        path: 'goods',
        component: () => import('@/components/menus/MyGoods.vue')
      },
      {
        path: 'detail/:id',
        component: () => import('@/components/user/MyUserDetail.vue')
      }
    ]
  },
  // 处理那些不存在的地址
  { path: '*', component: () => import('@/components/NotFound.vue') }
]

const router = new VueRouter({
  routes
})

// 添加全局前置导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
